import React, {Component} from 'react'
import {
    Button,
    Card,
    Col,
    Input,
    Row,
    Space,
    Table,
    Select,
    Tag,
    Popconfirm,
    Tooltip,
    message,
} from "antd";
import JobService from "../service/JobService";
import JobAdd from "./job_add"
import JobUpdate from "./job-update"
import {
    DeleteOutlined,
    RedoOutlined,
    PauseOutlined,
    EditOutlined,
    CaretRightOutlined,
    EyeOutlined
} from '@ant-design/icons';
import JobLogList from "./job-log-list";

const {Option} = Select;

class JobList extends Component {
    updateInfo = {};
    jobAddModal;
    logListModal;
    jobUpdateModal;
    // jobService封装了和后端交互的方法
    jobService = new JobService();
    state = {
        total: 0,
        visible: false,
        updateModalVisible: false,
        jobDataList: [],
        jobClassName: '',
        logModalVisible: false,
        searchCondition: {}

    };
    searchCondition = {
        pageSize: 10,
        pageNum: 1
    }




    // 定义表格字段
    columns = [
        {
            title: '任务名称',
            dataIndex: 'jobName',
            key: 'jobName',
        },
        {
            title: '任务所在组',
            dataIndex: 'jobGroup',
            key: 'jobGroup',
        },
        {
            title: '任务类名',
            dataIndex: 'jobClassName',
            key: 'jobClassName',
        },
        {
            title: '触发器名称',
            dataIndex: 'triggerName',
            key: 'triggerName',
        },
        {
            title: '触发器所在组',
            dataIndex: 'triggerGroup',
            key: 'triggerGroup',
        },
        {
            title: 'cron表达式',
            dataIndex: 'cronExpression',
            key: 'cronExpression',
        },
        {
            title: '时区',
            dataIndex: 'timeZoneId',
            key: 'timeZoneId',
        },
        {
            title: '状态',
            dataIndex: 'triggerState',
            key: 'triggerState',
            render: (triggerState) => {
                return <Tag color={'green'}>{triggerState}</Tag>;
            },

        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    {/*立即执行当前定时任务*/}
                    <Tooltip title="立即执行">
                        <Popconfirm title="立即执行当前任务?"
                                    onConfirm={() => this.triggerJob({
                                        jobGroupName: record.jobGroup,
                                        jobName: record.jobName
                                    })}
                                    okText="确定"
                                    cancelText="取消">
                            <Button shape={"circle"} icon={<CaretRightOutlined/>}/>
                        </Popconfirm>
                    </Tooltip>

                    {/*编辑定时任务*/}
                    <Tooltip title="编辑">
                        <Button shape={"circle"} icon={<EditOutlined/>}
                                onClick={() => this.showUpdateModal({
                                    triggerGroupName: record.triggerGroup,
                                    triggerName: record.triggerName
                                })}/>
                    </Tooltip>

                    <Tooltip title="暂停">
                        <Popconfirm title="暂定当前定时任务?"
                                    onConfirm={() => this.pauseJob({
                                        jobGroupName: record.jobGroup,
                                        jobName: record.jobName
                                    })}
                                    okText="确定"
                                    cancelText="取消">
                            <Button shape={"circle"} icon={<PauseOutlined/>}/>
                        </Popconfirm>
                    </Tooltip>

                    {/*重新开始定时任务*/}
                    <Tooltip title="重新开始">
                        <Popconfirm title="重新开始当前任务?"
                                    onConfirm={() => this.resumeJob({
                                        jobGroupName: record.jobGroup,
                                        jobName: record.jobName
                                    })}
                                    okText="确定"
                                    cancelText="取消">
                            <Button shape={"circle"} icon={<RedoOutlined/>}/>
                        </Popconfirm>
                    </Tooltip>
                    {/*删除定时任务*/}
                    <Tooltip title="删除">
                        <Popconfirm title="确定删除当前任务？此操作不可逆?"
                                    onConfirm={() => this.deleteJob({
                                        jobGroupName: record.jobGroup,
                                        jobClassName: record.jobClassName
                                    })}
                                    okText="确定"
                                    cancelText="取消">
                            <Button shape={"circle"} icon={<DeleteOutlined/>}/>
                        </Popconfirm>
                    </Tooltip>
                    {/*查看日志*/}
                    <Tooltip title="查看日志">
                        <Button shape={"circle"} icon={<EyeOutlined/>}
                                onClick={() => this.showLogList(record.jobClassName)}/>
                    </Tooltip>
                </Space>
            ),
        },
    ];


    /**
     * react 生命周期函数，在第一次渲染后调用，可以处理页面初始化时的前后端数据交互
     */
    componentDidMount() {
        this.search()
    }

    /**
     * table 监控回调，处理分页大小，以及分页编号的变化
     */
    handleTableChange = (pagination, filters, sorter) => {
        this.searchCondition = Object.assign(
            {}, this.searchCondition, {pageSize: pagination.pageSize, pageNum: pagination.current})
        this.search()
    };


    /**
     * 显示修改定时任务的对话框
     * @param jobInfo
     */
    showUpdateModal = (jobInfo) => {
        this.jobUpdateModal.showModal(jobInfo)
    }

    /**
     * 暂停任务
     * @param params
     */
    pauseJob = (params) => {
        this.jobService.pauseJob(params).then(resp => {
            const result = resp.data;
            if (result && result.code===0){
                message.success("已暂停")
                this.search()
            }else{
                message.error(result.message)
            }
        }).catch(err=>{
            message.error("系统错误，请联系管理员")
        })
    }

    /**
     * 恢复任务
     * @param params
     */
    resumeJob = (params) => {
        this.jobService.resumeJob(params).then(resp => {
            const result = resp.data;
            if (result && result.code===0){
                message.success("已恢复")
                this.search()
            }else{
                message.error(result.message)
            }
        }).catch(err=>{
            message.error("系统错误，请联系管理员")
        })
    }

    /**
     * 删除任务
     * @param params
     */
    deleteJob = (params) => {
        this.jobService.deleteJob(params).then(resp => {
            const result = resp.data;
            if (result && result.code===0){
                message.success("已删除")
                this.search()
            }else{
                message.error(result.message)
            }
        }).catch(err=>{
            message.error("系统错误，请联系管理员")
        })
    }

    /**
     * 立即执行任务
     * @param params
     */
    triggerJob = (params) => {
        this.jobService.triggerJob(params).then(resp => {const result = resp.data;
            if (result && result.code===0){
                message.success("已执行")
            }else{
                message.error(result.message)
            }
        }).catch(err=>{
            message.error("系统错误，请联系管理员")
        })
    }


    /**
     * 显示添加任务的对话框
     */
    showModal = () => {
        this.jobAddModal.showModal();
    };

    /**
     * 显示日志列表
     * @param jobClassName
     */
    showLogList = (jobClassName) => {
        this.logListModal.showModal(jobClassName);
    }

    /**
     * 搜索定时任务列表
     */
    search = () => {
        this.jobService.getList(Object.assign({},this.state.searchCondition, this.searchCondition)).then(resp => {
            console.log(resp)
            let data = resp['data'];
            if (data && data['code'] === 0) {
                this.setState({
                    jobDataList: data.data.list,
                    total: data.data.total,
                    pagination: {
                        total: data.data.total,
                    }
                })
            }else{
                message.error(data.message)
            }
        }).catch(err => {
            console.log(err)
           message.error("系统错误，请联系管理员")
        })
    }

    /**
     * 修改搜索条件 任务名称触发的回调
     * @param e
     */
    jobNameChange = (e) => {
        let value = e.target.value;
        let searchCondition = Object.assign({}, this.state.searchCondition, {jobName: value})
        if (value) {
            this.setState({
                searchCondition: searchCondition
            })
        }
    }

    /**
     * 修改搜索条件 任务所在组名称触发的回调
     * @param e
     */
    jobGroupNameChange = (e) => {
        let value = e.target.value;
        let searchCondition = Object.assign({}, this.state.searchCondition, {jobGroupName: value})
        if (value) {
            this.setState({
                searchCondition: searchCondition
            })
        }
    }

    /**
     * 修改搜索条件 任务类称触发的回调
     * @param e
     */
    jobClassNameChange = (e) => {
        let value = e.target.value;
        let searchCondition = Object.assign({}, this.state.searchCondition, {jobClassName: value})
        if (value) {
            this.setState({
                searchCondition: searchCondition
            })
        }
    }

    /**
     * 修改搜索条件 任务状态触发的回调
     * @param value
     */
    triggerStateChange = (value) => {
        let searchCondition = Object.assign({}, this.state.searchCondition, {triggerState: value})
        if (value) {
            this.setState({
                searchCondition: searchCondition
            })
        }
    }

    /**
     * 重置搜索条件
     */
    reset = () => {
        /*setState异步执行，所以可能在值还没有修改完成的时候就会继续执行下面的代码，所以有些时候需要同步执行的代码需要放到回调里*/
        this.setState({
            searchCondition:{}
        },()=>{ this.search()})

    }

    /**
     * 返回具体的dom
     * @returns {*}
     */
    render() {
        return <div className="site-layout-background" style={{padding: 24, minHeight: 380}}>
            <Card>
                <Row style={{marginBottom: 20}}>
                    <Input placeholder="请输入定时任务名称" style={{width: 200, marginRight: 12}} onChange={this.jobNameChange}
                           value={this.state.searchCondition.jobName}/>
                    <Input placeholder="请输入定时任务执行类名" style={{width: 200, marginRight: 12}}
                           onChange={this.jobClassNameChange} value={this.state.searchCondition.jobClassName}/>
                    <Input placeholder="请输入分组名称" style={{width: 200, marginRight: 12}}
                           onChange={this.jobGroupNameChange} value={this.state.searchCondition.jobGroupName}/>
                    <Select placeholder="请选择状态" style={{width: 120}} onChange={this.triggerStateChange}
                            value={this.state.searchCondition.triggerState}>
                        <Option value="ACQUIRED">运行中</Option>
                        <Option value="PAUSED">暂停中</Option>
                    </Select>

                    <Button type="primary" style={{marginLeft:12,marginRight: 12}} onClick={this.search}>搜索</Button>
                    <Button type="primary" style={{marginRight: 12}} onClick={this.reset}>重置</Button>
                    <Button type="primary" onClick={this.showModal}>添加</Button>
                </Row>

                <Row>
                    <Col span={24}>
                        <Table dataSource={this.state.jobDataList} pagination={this.state.pagination} rowKey="jobClassName"
                               columns={this.columns} total={this.state.total} onChange={this.handleTableChange}/>
                    </Col>

                </Row>
            </Card>
            <JobAdd onRef={(ref) => {
                this.jobAddModal = ref
            }} refreshJobList={this.search}/>
            <JobUpdate updateInfo={this.updateInfo} onRef={(ref) => {
                this.jobUpdateModal = ref
            }} refreshJobList={this.search}/>
            <JobLogList jobClassName={this.state.jobClassName} onRef={(ref) => {
                this.logListModal = ref
            }}/>
        </div>
    }
}

export default JobList